<?php
/**
 * Created by PhpStorm.
 * User: majiawen
 * Date: 2018/3/5
 * Time: 16:10
 */

namespace app\admin\controller\v1;

use app\admin\controller\Fun;
use app\common\Model\Region;
use think\Db;


/**
 * @title 后台-捎货管理-加盟商管理-V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class Franchiser extends Base
{
    /**
     * @title 加盟商管理列表
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Franchiser desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:franchiserList desc:加盟商管理列表
     *
     * @param name:page type:string require:1 default: other: desc:页码
     * @param name:page_size type:string require:1 default: other: desc:每页个数
     * @param name:search type:string require:1 default: other: desc:查询数据
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     *
     * @return data:['list'=>[],'total_num'=>2 ]
     */
    public function franchiserList()
    {
        $where = [
            'user_type' => \app\common\Model\AdminUser::USER_TYPE_FRANCHISER,
        ];
        //查询
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];
            $where['realname|phone|create_time'] = ['like', '%' . $search . '%'];
        }
        $used_sort_field = [
            'uid', 'realname', 'phone', 'status', 'create_time', 'update_time', 'name',
        ];
        if (isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'], $used_sort_field) && isset($this->param['sort_type'])) {
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        } else {
            $order = ['u.uid' => $this->sort_type[1]];
        }
        $list = Db::name('admin_user u')
            ->where($where)
            ->order($order)
            ->field('
            u.uid ,
            u.realname ,
            u.phone ,
            u.status ,
            u.update_time
            ')
            ->paginate($this->page_size, false, ['page' => $this->param['page']]);
        if ($list) {
            $AdminUser = new \app\common\Model\AdminUser();
            $data = [];
            foreach ($list->items() as $k => $v) {
                $arr = $v;
                $arr['status'] = $AdminUser->_status[$v['status']];
                $arr['_status'] = $v['status'];
                $arr['regions'] = Db::name('region')->where('au_id', $v['uid'])->field('region_id,name,parent_id')->select();
                foreach ($arr['regions'] as $key => $value) {
                    $province = Db::name('region')->where('region_id', $value['parent_id'])->field('region_id,name')->find();
                    unset($arr['regions'][$key]['parent_id']);
                    $arr['regions'][$key]['provinceid'] = $province['region_id'];
                    $arr['regions'][$key]['provincename'] = $province['name'];
                }
                $data[] = $arr;
            }
            return Fun::success([
                'list' => $data,
                'total_num' => $list->total()
            ]);
        } else {
            return Fun::error('333333');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 添加修改加盟商
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Franchiser desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:addFranchiser desc:添加修改加盟商
     *
     * @param name:realname type:string require:1 default: other:中国移动 desc:姓名
     * @param name:phone type:string require:1 default: other:1008611 desc:手机号
     * @param name:passwd type:string require:1 default: other:111111 desc:密码
     * @param name:region_ids type:string require:1 default: other:110000,220000 desc:管辖区域
     * @param name:status type:string require:1 default: other: desc:用户状态:0正常,1禁用
     * @param name:uid type:string require:1 default: other: desc:要修改的用户ID
     * 
     * @return data:[]
     */
    public function addFranchiser()
    {
        if (empty($this->param['realname']) || empty($this->param['phone']) || !isset($this->param['region_ids']) || !isset($this->param['status'])) {
            return Fun::error('999994');//TODO 无数据，定义错误类型
        }
        //检测手机号是否重复
        $AU = new \app\common\Model\AdminUser();
        $uid = $this->param['uid'] ?? (\app\common\Model\AdminUser::get(['phone' => $this->param['phone']])->uid ?? 0);
        $userFind = $AU->where('uid', $uid)->find();

        // 启动事务
        Db::startTrans();
        try {

            if ($uid) {

                //存在,则修改
                $AU = $userFind;
            }
            //region_ids为空时,添加或修改代理区域为空
            if(empty($this->param['region_ids'])){
                $region_ids = [-1];
            }else{
                $region_ids = explode(',', trim($this->param['region_ids'], ','));
            }
            $where = [
                'region_id' => ['in', $region_ids]
            ];

            //加盟商已管辖区域排除
            if (!empty($AU->uid)) {
                $checkRegionWhere['au_id'] = ['<>', $AU->uid];
            }else{
                $checkRegionWhere = [];
            }

            //判断加盟商的城市是否有效
            $region = Db::name('region')->where($where)->column('region_id');
            if($region!=$region_ids){
                return Fun::error('802004');
            }

            //检测区域是否已代理
            foreach ($region as $k => $v) {
                $res = $this->checkRegion($v,$checkRegionWhere);
                if ($res) {
                    return Fun::error('802003', $res);
                }
            }

            $AU->acc_id = GenToken();
            $AU->realname = $this->param['realname'];
            $AU->phone = $this->param['phone'];
            $AU->status = intval($this->param['status'])==0?'0':1;
            if(!empty($this->param['passwd'])){
                $AU->passwd = Fun::encryptPwd($this->param['passwd']);
            }
            $AU->user_type = 1;
            $AU->save();

            Db::name('region')->where(['au_id' => $AU->uid])->update(['au_id' => 0]);
            if(count($region))
            {
                Db::name('region')->where(['region_id' => ['in', $region]])->update(['au_id' => $AU->uid]);
            }

            // 提交事务
            Db::commit();
            return Fun::success('操作成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return Fun::error('333332');//TODO 无数据，定义错误类型
        }
    }

    //根据当前加盟商查询,判断当前区域是否可以授权
    private function checkRegion($region_id,$where)
    {
        $Region = new Region();
        $res = $Region
            ->where(['region_id' => $region_id])
            ->find();
        if ($res->level == 1) {
            $ret = $Region
                ->where($where)
                ->where([
                'au_id' => ['>', 0],
                'region_id' => ['between', [$res->region_id, $res->region_id + 9999]],
            ])->find();
        } elseif ($res->level == 2) {
            $ret = $Region
                ->where($where)
                ->where([
                'au_id' => ['>', 0],
                'region_id' => $res->parent_id,
            ])->find();
            if ($ret) {
                return $ret->name;
            }
            $ret = $Region
                ->where($where)
                ->where([
                'au_id' => ['>', 0],
                'region_id' => ['between', [$res->region_id, $res->region_id + 99]],
            ])->find();
        } elseif ($res->level == 3) {
            // $ret = $Region
            //     ->where($where)
            //     ->where([
            //     'au_id' => ['>', 0],
            //     'region_id' => ['in', [$res->region_id, $res->parent_id, floor($res->parent_id / 10000) * 10000]],
            // ])->find();

            //父加盟商只能选择市，子加盟商只能选择区，判断这个区域是否有其他子加盟商开通
            $ret = $Region
                ->where($where)
                ->where([
                'aus_id' => ['>', 0],
                'region_id' => ['eq', $res->region_id],
            ])->find();            
        }
        if (!empty($ret)) {
            return $ret->name;
        }
        return false;
    }

    /**
     * @title 添加修改子加盟商
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Franchiser desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:addSonFranchiser desc:添加修改子加盟商
     *
     * @param name:pid type:string require:1 default: other: desc:父ID
     * @param name:realname type:string require:1 default: other:中国移动 desc:姓名
     * @param name:phone type:string require:1 default: other:1008611 desc:手机号
     * @param name:passwd type:string require:1 default: other:111111 desc:密码
     * @param name:region_ids type:string require:1 default: other:110000,220000 desc:管辖区域
     * @param name:status type:string require:1 default: other: desc:用户状态:0正常，1锁定
     *
     * @return data:[]
     */
    public function addSonFranchiser()
    {
        if (empty($this->param['pid']) || empty($this->param['realname']) || empty($this->param['phone']) || !isset($this->param['region_ids']) || !isset($this->param['status'])) {
            return Fun::error('999994');//TODO 无数据，定义错误类型
        }
        //检测手机号是否存在
        $AU = new \app\common\Model\AdminUser();
        $phone = $AU->where('phone', $this->param['phone'])->find();

        // 启动事务
        Db::startTrans();
        try {

            if ($phone) {
                //存在,属于该加盟商,修改
                if($phone->pid==$this->param['pid']){
                    $AU = $phone;
                }else{
                    //存在,不属于该加盟商,返回"该手机号已绑定"
                    return Fun::error('801006');
                }
            }else{
                //新增子加盟商
                $AU->pid = $this->param['pid'];
            }
            //region_ids为空时,添加或修改代理区域为空
            if(empty($this->param['region_ids'])){
                $region_ids = [-1];
            }else{
                $region_ids = explode(',', trim($this->param['region_ids'], ','));
            }
            $where = [
                'au_id' =>$AU->pid,
                // 'region_id' => ['in', $region_ids],
            ];
            //在父加盟商中查找,并将子加盟商已管辖区域排除,子加盟商在region表中aus_id表示
            $checkRegionWhere['au_id'] = $AU->pid;
            if (!empty($AU->uid)) {
                $checkRegionWhere['aus_id'] = ['<>', $AU->uid];
            }else{
                $checkRegionWhere = [];
            }
            //检测区域是否属于父加盟商
            $region = Db::name('region')->where($where)->column('region_id');
            foreach ($region_ids as $key => $value) {
                $parent = Db::name('region')->where(['region_id'=>$value])->field('parent_id,name')->find();
                if (!in_array($parent['parent_id'],$region)) {
                    return Fun::error('802004', $parent['name']);
                }
            }

            //检测区域是否已代理
            foreach ($region_ids as $k => $v) {
                $res = $this->checkRegion($v,$checkRegionWhere);
                if ($res) {
                    return Fun::error('802003', $res);
                }
            }
            $AU->acc_id = GenToken();
            $AU->realname = $this->param['realname'];
            $AU->phone = $this->param['phone'];
            $AU->status = intval($this->param['status'])==0?'0':1;
            if(!empty($this->param['passwd'])){
                $AU->passwd = Fun::encryptPwd($this->param['passwd']);
            }
            $AU->user_type = 1;
            $AU->save();

            if(count($region_ids))
            {
                //清除原有,再添加
                // Db::name('region')->where(['au_id' => $AU->uid])->update(['au_id' => 0]);
                Db::name('region')->where(['aus_id' => $AU->uid])->update(['aus_id' => 0]);
                Db::name('region')->where(['region_id' => ['in', $region_ids]])->update(['aus_id' => $AU->uid]);   
            }

            // 提交事务
            Db::commit();
            return Fun::success('添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return Fun::error('333332');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 加盟商详情
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Franchiser desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:franchiserDetail desc:加盟商详情
     *
     * @param name:uid:string require:1 default: other: desc:加盟商的UID
     *
     * @return data:['list'=>[],'total_num'=>2 ]
     */
    public function franchiserDetail()
    {
        //uid不能为空
        if (empty($this->param['uid'])) {
            return Fun::error('999994');//TODO 无数据，定义错误类型
        }
        $AdminUser = new \app\common\Model\AdminUser();
        $user = $AdminUser->where(['uid'=>$this->param['uid']])->field('uid,realname,phone,status')->find();
        if (empty($user->uid)) {
            return Fun::error('100000');//TODO 无数据，定义错误类型
        }
        $region = new Region();
        $user->__status = $user->status;
        $user->status = $AdminUser->_status[$user->status];
        $user->region_info = $region->where(['au_id'=>$user->uid])->field('region_id,name')->select();
        $users = $AdminUser::where(['pid'=>$user->uid])->field('uid,realname,phone,status')->select();
        $data = [];
        foreach ($users as $k => $v){
            $v->__status = $v->status;
            $v->status = $AdminUser->_status[$v->status];
            $region = Db::name('region')->where(['aus_id'=>$v->uid])->field('region_id,name,parent_id')->select();
            foreach ($region as $key => $value) {
                $parent = Db::name('region')->where(['region_id'=>$value['parent_id']])->field('region_id,name')->find();
                $region[$key]['parent_region'] = $parent['region_id'];
                $region[$key]['parent_name'] = $parent['name'];
            }
            $v->region_info = $region;
            $data[] = $v;
        }
        $user->son = $data;
        return Fun::success($user);
    }


    /**
     * @title 修改加盟商状态
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Franchiser desc:接口组(全局)
     * @header name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:command type:string require:1 default: other:alterFranchiserStatus desc:捎货人禁用恢复
     *
     * @param name:ids type:string require:1 default: other:10086,10087,10088 desc:用户id
     * @param name:status type:string require:1 default: other:0 desc:加盟商状态:1有效,0禁用
     *
     * @return data:[]
     */
    public function alterFranchiserStatus()
    {
        if(empty($this->param['ids'])){
            return Fun::error('');//TODO 无数据，定义错误类型
        }
        $ids = explode(',', trim($this->param['ids'], ','));
        $updata = [];

        $AdminUser = New \app\common\Model\AdminUser();
        //用户状态:1为有效,0为禁用
        if (isset($this->param['status']) && in_array(intval($this->param['status']), [$AdminUser::STATUS_NORMAL,$AdminUser::STATUS_FORBID])) {
            $updata['status'] = $this->param['status'];
        }else{
        return Fun::error('333332');//TODO 无数据，定义错误类型
            return Fun::error('');//TODO 无数据，定义错误类型
        }
        if (count($updata) && count($ids)) {
            $AdminUser->where('uid', 'in', $ids)
                ->update($updata);
            return Fun::success('');
        }
        return Fun::error('333332');//TODO 无数据，定义错误类型
    }
}